/*
 * @Author: Jone XIn
 * @Date: 2022-01-10 23:44:59
 * @LastEditTime: 2022-01-23 23:33:56
 * @Description: 通用工具函数
 */
const os = require('os');
const path = require('path');
const fs = require('fs-extra');
/**
 * 获取本机IP
 * @returns Ip
 */
const getLocalIp = () => {
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}

/**
 * @param {时间戳} date
 * @returns 格式化后的时间
 */
function formatDate(date) {
    let time = new Date(date);
    let minites = time.getMinutes() < 10 ? `0${time.getMinutes()}` : time.getMinutes();
    let seconds = time.getSeconds() < 10 ? `0${time.getSeconds()}` : time.getSeconds();
    return `${time.toLocaleDateString()} ${time.getHours()}:${minites}:${seconds}`;
}

/**
 * 处理文件的地址
 * @param {Object} fileInfo
 * @returns  newFilePath【本地文件的存储路径】
 */
function handProjectPath(fileInfo) {
    let { project_name, project_path, filePath } = fileInfo;
    let filePathArr, project_pathArr;
    if (os.type == 'Windows_NT') {
        filePathArr = filePath.split(path.sep);
        project_pathArr = project_path.split(path.sep);
        return project_pathArr.slice(0, project_pathArr.indexOf(project_name)).concat(filePathArr.slice(filePathArr.indexOf(project_name))).join('\\');
    }
    filePathArr = filePath.split(path.sep);
    project_pathArr = project_path.split(path.sep);
    return project_pathArr.slice(0, project_pathArr.indexOf(project_name)).concat(filePathArr.slice(filePathArr.indexOf(project_name))).join('/');
}

/**
 * 创建指定文件路径【可能有多重新的文件夹】
 * @param {string} filePath
 * @returns 创建成功与否 boolean
 */
function createFileAbsolute(filePath) {
    try {
        const dir = filePath.split(path.sep);
        if (fs.pathExistsSync(filePath)) return true;
        dir.map((item, index) => {
            const dirPath = dir.slice(0, index + 1).join(os.type() == 'Windows_NT' ? '\\' : '/');
            // 某个路径不存在，创建
            console.log(fs.pathExistsSync(dirPath), path.extname(dirPath));
            if (!fs.pathExistsSync(dirPath) && index > 0 && !path.extname(dirPath)) {
                fs.mkdirpSync(dirPath);
            }
            if (index == dir.length - 1 && path.extname(dirPath)) {
                fs.writeFileSync(dirPath, '', 'utf-8');
            }
        })
        return true;
    } catch (_) {
        console.log(_);
        return false;
    }
}

module.exports = {
    getLocalIp,
    formatDate,
    handProjectPath,
    createFileAbsolute
};